package com.zshy.base.core.validate;

import com.zshy.base.core.contract.enums.EnumValue;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Objects;

/**
 * 枚举值校验
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2024/2/2 15:08
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;

    private int[] intValues;

    private boolean ignoreNull;

    /**
     * 初始化
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(EnumValue constraintAnnotation) {
        this.strValues = constraintAnnotation.strValues();
        this.intValues = constraintAnnotation.intValues();
        this.ignoreNull = constraintAnnotation.ignoreNull();
    }

    /**
     * 参数校验
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (Objects.isNull(value) && this.ignoreNull) {
            return true;
        }
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s == value) {
                    return true;
                }
            }
        }
        return false;
    }
}
